package cn.itsource.basic.controller;

import cn.itsource.basic.util.AjaxResult;
import cn.itsource.basic.util.FastdfsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping("/fast_dfs")
@Slf4j
public class UploadController {

    @PostMapping("/upload")
    public AjaxResult upload(@RequestPart MultipartFile file) throws Exception {
        //得到文件字节数组
        byte[] bytes = file.getBytes();
        //获取文件扩展名，后缀
        String filename = file.getOriginalFilename();
        String extname = filename.substring(filename.indexOf(".") + 1);
        //上传
        String path = FastdfsUtil.upload(bytes, extname);
        return AjaxResult.me().setResultObj(path);
    }

    @PostMapping("/del")
    public AjaxResult del(@RequestBody Map<String,String> map){
        String path = map.get("path"); // group1/xxx/xxx/xxxxx.jpg
        log.info("接收到的路径是{}",path);
        //获取group
        int index = path.indexOf("/");
        String group = path.substring(0,index);
        log.info("我要删除的group是{}",group);
        //获取文件
        String filePath = path.substring(index+1);
        log.info("我要删除的文件路径是{}",filePath);
        FastdfsUtil.delete(group,filePath);
        return AjaxResult.me();
    }
}
